import SwiperList from "@/components/SwiperList";
import { AppContext } from "@/layouts/Main";
import React, { useState, useRef, useEffect, useContext, memo, FC, ChangeEvent } from "react";
import { useNavigate } from "react-router-dom";
import { m, AnimatePresence } from "framer-motion";
import styles from "./Dashboard.module.scss";
import { Card, Carousel, Form, Input, message, Modal, Tooltip } from "antd";
const { Meta } = Card;
import { useInView, animated } from "@react-spring/web";
import { wrap } from "popmotion";
import coumt1 from "@/assets/images/common/custom1.jpg";
import coumt2 from "@/assets/images/common/custom2.jpg";
import { Swiper, SwiperSlide } from 'swiper/react';
import { Navigation, Pagination, Scrollbar, A11y, Autoplay, EffectFade, EffectFlip, EffectCards } from 'swiper/modules';
import 'swiper/css/navigation';
import 'swiper/css/pagination';
import 'swiper/css/scrollbar';
import 'swiper/css';
import 'swiper/css/effect-fade'
import 'swiper/css/effect-flip'
import orgService from "@/api/index";
const SlideIn = function ({ list, type }: any) {
  return (
    <>
      {list.map((item: any, index: any) => {
        return <SlideInItem key={index} item={item} types={type}></SlideInItem>;
      })}
    </>
  );
};

const SlideInItem = memo(function SlideInItem({ item, types }: any) {
  let item1 = item && item[1];
  let item2 = item && item[2];
  let item3 = item && item[3];

  const [ref, inView] = useInView({ once: true });

  const [ref1, inView1] = useInView({ once: true });
  const [ref2, inView2] = useInView({ once: true });
  const navigate = useNavigate();
  const goDetail = (item: any) => {
    navigate("/detail" + "?id=" + item.id, { replace: true, state: { query: item?.id } });
  };
  return (
    <div className="mt-20">
      <div className="w-1200px mx-auto ">
        {types == 1 && (
          <div className="flex flex-col items-center cursor-pointer">
            <div className="flex items-center">
              <div className={styles["ev-line-1"]}></div>
              <div className="text-4xl mr-5 ml-5 font-medium" style={{ color: '#4096ff' }}>当季热销</div>
              <div className={styles["ev-line-2"]}></div>
            </div>
            <div
              ref={ref}
              className={`flex mt-10 ${inView ? "animate__animated animate__fadeInUp" : ""
                }`}
              style={{ width: "100%" }}
            >
              {item1 && (
                <Card
                  onClick={() => {
                    goDetail(item1[0]);
                  }}
                  className="mr-5"
                  style={{ width: "800px", height: "600px" }}
                  hoverable
                  cover={
                    <Swiper
                      modules={[Navigation, Pagination, Scrollbar, A11y, Autoplay, EffectFade, EffectFlip, EffectCards]}
                      spaceBetween={10}
                      slidesPerView={1}
                      loop={true}
                      pagination={{ clickable: true }}
                      style={{ height: "440px", width: "476px" }}
                      autoplay
                      effect="cards"
                    >
                      {item1[0].titleUrl && item1[0].titleUrl.split(",").map((item: any, index: any) => {
                        return <SwiperSlide style={{ height: "440px", width: "476px" }}>
                          <img key={index} src={item} className="w-full h-full"></img>
                        </SwiperSlide>
                      })}
                    </Swiper>
                  }
                >
                  <Meta
                    title={item1[0].name}
                    className="line-clamp-3"
                    description={`${item1[0].pDesc}`}
                  />
                </Card>
              )}
              <div className="container flex flex-wrap justify-between">
                {item1 &&
                  item1.slice(1, 5).map((item: any, index: number) => {
                    return (
                      <div
                        key={index}
                        className="item"
                        onClick={() => {
                          goDetail(item);
                        }}
                      >
                        <img
                          className="hover:scale-105 transition-transform duration-300 shadow-xl rounded-md"
                          style={{ width: "340px", height: "200px" }}
                          src={item.titleUrl.split(",")[0]}
                        />
                        <div
                          className="hover:text-blue-500 pt-2  line-clamp-2"
                          style={{ width: "340px", fontWeight: "600" }}
                        >
                          {item.name}
                        </div>
                        <div
                          className=" line-clamp-2 mt-2 text-sm"
                          style={{
                            width: "340px",
                            color: "rgba(0, 0, 0, 0.45)",
                          }}
                        >
                          {item.pDesc}
                        </div>
                      </div>
                    );
                  })}
              </div>
            </div>
          </div>
        )
        }

        {types == 2 && (
          <div className="flex flex-col items-center  cursor-pointer">
            <div className="flex items-center">
              <div className={styles["ev-line-1"]}></div>
              <div className="text-4xl mr-5 ml-5 font-medium" style={{ color: '#4096ff' }}>精品课程</div>
              <div className={styles["ev-line-2"]}></div>
            </div>
            <div
              ref={ref1}
              className={`flex mt-10 ${inView1 ? "animate__animated animate__fadeInUp" : ""
                }`}
              style={{ width: "100%" }}
            >
              {item2 && (
                <Card
                  onClick={() => {
                    goDetail(item2[0]);
                  }}
                  className="mr-5"
                  style={{ width: "800px", height: "600px" }}
                  hoverable
                  cover={
                    <Swiper
                      modules={[Navigation, Pagination, Scrollbar, A11y, Autoplay, EffectFade, EffectFlip, EffectCards]}
                      spaceBetween={10}
                      slidesPerView={1}
                      loop={true}
                      pagination={{ clickable: true }}

                      style={{ height: "440px", width: "476px" }}
                      autoplay
                      effect="cards"
                    >
                      {item2[0].titleUrl && item2[0].titleUrl.split(",").map((item: any, index: any) => {
                        return <SwiperSlide style={{ height: "440px", width: "477px" }}>
                          <img key={index} src={item} className="w-full h-full"></img>
                        </SwiperSlide>
                      })}
                    </Swiper>
                  }
                >
                  <Meta
                    title={item2[0].name}
                    className="line-clamp-3"
                    description={item2[0].pDesc}
                  />
                </Card>
              )}

              <div className="container flex flex-wrap justify-between">
                {item2 &&
                  item2.slice(1, 5).map((item: any, index: number) => {
                    return (
                      <div
                        key={index}
                        className="item"
                        onClick={() => {
                          goDetail(item);
                        }}
                      >
                        <img
                          className="hover:scale-105 transition-transform duration-300 shadow-xl rounded-md"
                          style={{ width: "340px", height: "200px" }}
                          src={item.titleUrl.split(",")[0]}
                        />
                        <div
                          className="hover:text-blue-500 pt-2  line-clamp-2"
                          style={{ width: "340px", fontWeight: "600" }}
                        >
                          {item.name}
                        </div>
                        <div
                          className=" line-clamp-2 mt-2 text-sm"
                          style={{
                            width: "340px",
                            color: "rgba(0, 0, 0, 0.45)",
                          }}
                        >
                          {item.pDesc}
                        </div>
                      </div>
                    );
                  })}
              </div>
            </div>
          </div>
        )}

        {
          types == 3 && (
            <div className="flex flex-col items-center cursor-pointer">
              <div className="flex items-center">
                <div className={styles["ev-line-1"]}></div>
                <div className="text-4xl mr-5 ml-5 font-medium" style={{ color: '#4096ff' }}>场地推荐</div>
                <div className={styles["ev-line-2"]}></div>
              </div>
              <div
                ref={ref2}
                className={`flex mt-10 ${inView2 ? "animate__animated animate__fadeInUp" : ""
                  }`}
                style={{ width: "100%" }}
              >
                {item3 && (
                  <Card
                    onClick={() => {
                      goDetail(item3[0]);
                    }}
                    className="mr-5"
                    style={{ width: "800px", height: "600px" }}
                    hoverable
                    cover={
                      <Swiper
                        modules={[Navigation, Pagination, Scrollbar, A11y, Autoplay, EffectFade, EffectFlip, EffectCards]}
                        spaceBetween={10}
                        slidesPerView={1}
                        loop={true}

                        pagination={{ clickable: true }}

                        style={{ height: "440px", width: "476px" }}
                        autoplay
                        effect="cards"
                      >
                        {item3[0].titleUrl && item3[0].titleUrl.split(",").map((item: any, index: any) => {
                          return <SwiperSlide style={{ height: "440px", width: "477px" }}>
                            <img key={index} src={item} className="w-full h-full"></img>
                          </SwiperSlide>
                        })}
                      </Swiper>
                    }
                  >
                    <Meta
                      title={item3[0].name}
                      className="line-clamp-3"
                      description={`${item3[0].pDesc}`}
                    />
                  </Card>
                )}

                <div className="container flex flex-wrap justify-between">
                  {item3 &&
                    item3.slice(1, 5).map((item: any, index: number) => {
                      return (
                        <div
                          key={index}
                          className="item"
                          onClick={() => {
                            goDetail(item);
                          }}
                        >
                          <img
                            className="hover:scale-105 transition-transform duration-300 shadow-xl rounded-md"
                            style={{ width: "340px", height: "200px" }}
                            src={item.titleUrl.split(",")[0]}
                          />
                          <div
                            className="hover:text-blue-500 pt-2  line-clamp-2"
                            style={{ width: "340px", fontWeight: "600" }}
                          >
                            {item.name}
                          </div>
                          <div
                            className=" line-clamp-2 mt-2 text-sm"
                            style={{
                              width: "340px",
                              color: "rgba(0, 0, 0, 0.45)",
                            }}
                          >
                            {item.pDesc}
                          </div>
                        </div>
                      );
                    })}
                </div>
              </div>
            </div>
          )
        }
      </div >
    </div >
  );
});

const CustomQy = () => {
  const images = [coumt1, coumt2];
  const [ref, inView] = useInView({ once: true });

  const variants = {
    enter: (direction: number) => {
      return {
        x: direction > 0 ? 100 : -100,
        opacity: 0,
      };
    },
    center: {
      zIndex: 1,
      x: 0,
      opacity: 1,
    },
    exit: (direction: number) => {
      return {
        zIndex: 0,
        x: direction < 0 ? 100 : -100,
        opacity: 0,
      };
    },
  };

  const [[page, direction], setPage] = useState([0, 0]);

  const imageIndex = wrap(0, images.length, page);

  const paginate = (newDirection: number) => {
    setPage([page + newDirection, newDirection]);
  };

  const swipeConfidenceThreshold = 10000;
  const swipePower = (offset: number, velocity: number) => {
    return Math.abs(offset) * velocity;
  };

  useEffect(() => {

    //Implementing the setInterval method 
    const interval = setInterval(() => {
      paginate(1)
    }, 3000);

    //Clearing the interval 
    return () => clearInterval(interval);
  }, [page]);

  return (
    <div className="w-1200px mx-auto h-full relative">
      <div
        ref={ref}
        className={`flex flex-col items-center mt-10 w-full ${inView ? "animate__animated animate__fadeInUp" : ""
          }`}
      >
        <div className="flex items-center">
          <div className={styles["ev-line-1"]}></div>
          <div className="text-4xl mr-5 ml-5 text-blue-500 font-medium">合作企业</div>
          <div className={styles["ev-line-2"]}></div>
        </div>
      </div>
      <div className={styles["container"]}>
        <AnimatePresence initial={true} custom={direction}>
          <m.img
            className={styles["img"]}
            key={page}
            src={images[imageIndex]}
            custom={direction}
            variants={variants}
            initial="enter"
            animate="center"
            exit="exit"
            transition={{
              x: { type: "spring", stiffness: 500, damping: 20 },
              opacity: { duration: 0.2 },
            }}
            drag="x"
            dragConstraints={{ left: 0, right: 0 }}
            dragElastic={1}
            onDragEnd={(e: any, { offset, velocity }: any) => {
              const swipe = swipePower(offset.x, velocity.x);

              if (swipe < -swipeConfidenceThreshold) {
                paginate(1);
              } else if (swipe > swipeConfidenceThreshold) {
                paginate(-1);
              }
            }}
          />
        </AnimatePresence>
        <div className={styles["next"]} onClick={() => paginate(1)}>
          {"‣"}
        </div>
        <div className={styles["prev"]} onClick={() => paginate(-1)}>
          {"‣"}
        </div>
      </div>
    </div>
  );
};

const CustomMenu: FC = () => {
  const listCard = [
    {
      name: '需求提交',
      description: 'Demand communication',
      descriptionDetail: '在线电话提交活动基本需求以及您的联系方式'
    },
    {
      name: '需求匹配',
      description: 'Demand matching',
      descriptionDetail: '客服会与您初步沟通，并需求匹配相应经验丰富的活动顾问'
    },
    {
      name: '需求沟通',
      description: 'Demand communication',
      descriptionDetail: '活动顾问通过顾问咨询技术，细致了解客服需求，确定项目流程与时间计划'
    }, {
      name: '方案策划',
      description: 'Scheme planning',
      descriptionDetail: '签订服务合同，活动顾问根据客户需求设计货方案，包括策划思路、活动细节、执行流程、资源准备等'
    }
    , {
      name: '活动执行',
      description: 'Activity execution',
      descriptionDetail: '项目经理按照项目计划表协调各方面资源有序推进，执行团队按照敲定的执行单现场把控落地执行，确保活动项目顺利实施'
    }
    , {
      name: '体验反馈',
      description: 'Experience feedback',
      descriptionDetail: '活动结束后，柠聚会对执行过程中所有监控数据进行汇总分析，并通过满意度调查对活动体验的反馈'
    }
  ]

  const [ref, inView] = useInView({ once: true });
  const [names, setNames] = useState<any>("")
  const [phone, setPhone] = useState<any>("")
  const [concatName, setConcatName] = useState<any>("")
  const [goodsName, setgoodsName] = useState<any>("")

  const textChangeHandler = (event: ChangeEvent) => {
    setNames((event.target as HTMLInputElement).value);
  };

  const textChangeHandler1 = (event: ChangeEvent) => {
    setPhone((event.target as HTMLInputElement).value);
  };

  const textChangeHandler2 = (event: ChangeEvent) => {
    setConcatName((event.target as HTMLInputElement).value);
  };

  const textChangeHandler3 = (event: ChangeEvent) => {
    setgoodsName((event.target as HTMLInputElement).value);
  };

  const saveHandle = () => {
    if (!names) {
      return message.warning('请输入公司名称')

    }
    if (!phone) {
      return message.warning('请输入联系电话')
    }
    if (!goodsName) {
      return message.warning('请输入产品名称')
    }
    if (!concatName) {
      return message.warning('请输入联系人')
    }

    orgService.saveQuestion({
      "def1": names,
      "def2": goodsName,
      "def3": concatName,
      "descp": phone,
    }).then(res => {
      if (res) {
        message.info('提交成功')
      }
    })
  }


  return (
    <>
      <div ref={ref}
        className={`mx-auto w-[1200px] mt-20flex mt-10 ${inView ? "animate__animated animate__fadeInUp" : ""
          }`} >
        <div className="flex w-full text-center items-center justify-center">
          <div className={styles["ev-line-1"]}></div>
          <div className="text-4xl mr-5 ml-5 text-blue-500 font-medium">服务流程</div>
          <div className={styles["ev-line-2"]}></div>
        </div>
        <div className="flex gap-2 mt-10">
          {
            listCard.map((item: any, index: number) => {
              return <div className="flex-1">
                <div
                  className="rounded-3xl relative overflow-hidden  h-80  cursor-pointer text-2xl font-bold bg-white"
                >
                  <div className="z-10 absolute w-full h-full peer"></div>
                  <div
                    className="absolute  peer-hover:-top-20 peer-hover:-left-16 peer-hover:w-[140%] peer-hover:h-[140%] -top-32 -left-16 w-32 h-44 rounded-full bg-slate-100 transition-all duration-500"
                  ></div>
                  <div
                    className="absolute rounded-sm rounded-full flex text-xl text-center items-end justify-end peer-hover:right-0 peer-hover:rounded-b-none peer-hover:bottom-0 peer-hover:items-center peer-hover:justify-center peer-hover:w-full peer-hover:h-full -bottom-32 -right-16 w-36 h-44  bg-blue-100 transition-all duration-500"
                  >
                    <div className="flex flex-col items-center justify-center">
                      <div className="text-3xl">
                        0{index + 1}
                      </div>
                      <div className="text-xs">
                        {item.name}
                      </div>
                      <div className="text-xs" style={{ color: 'rgba(0, 0, 0, 0.45)' }}>
                        {item.descriptionDetail}
                      </div>
                    </div>
                  </div>
                  <div className="w-full h-full items-center justify-center flex flex-col uppercase">
                    <div className=" text-3xl mb-10">
                      0{index + 1}
                    </div>
                    <div className="text-sm">
                      {item.name}
                    </div>
                    <div className="text-gray-400 text-xs">
                      {item.description}
                    </div>
                  </div>
                </div>
              </div>
            })
          }

        </div>
      </div>

      <div className="flex w-full text-center items-center justify-center mt-10">
        <div className={styles["ev-line-1"]}></div>
        <div className="text-4xl mx-5 text-blue-500 font-medium">个性化定制您专属方案</div>
        <div className={styles["ev-line-2"]}></div>
      </div>
      <div className="text-center text-xl  w-full mt-2 text-blue-500 font-medium">我们将竭尽所能为您提供最优质的服务</div>

      <div className="flex mt-10 gap-x-2 mx-auto items-center w-[1200px]">
        <div className="flex">
          <div className="relative">
            <input
              type="text"
              value={names}
              onChange={textChangeHandler}
              placeholder="公司名称"
              className="block w-full rounded-2xl border border-neutral-300 bg-transparent py-4 pl-6 pr-20 text-base/6 text-neutral-950 ring-4 ring-transparent transition placeholder:text-neutral-500 focus:border-blue-500  focus:outline-none focus:ring-neutral-950/5"
            />
            <div className="absolute inset-y-1 right-1 flex justify-end">

            </div>
          </div>
        </div>
        <div className="flex">
          <div className="relative">
            <input
              type="text"
              value={goodsName}
              onChange={textChangeHandler3}
              placeholder="产品名称"
              className="block w-full rounded-2xl border border-neutral-300 bg-transparent py-4 pl-6 pr-20 text-base/6 text-neutral-950 ring-4 ring-transparent transition placeholder:text-neutral-500 focus:border-blue-500  focus:outline-none focus:ring-neutral-950/5"
            />
            <div className="absolute inset-y-1 right-1 flex justify-end">

            </div>
          </div>
        </div>
        <div className="flex">
          <div className="relative">
            <input
              type="text"
              value={concatName}
              onChange={textChangeHandler2}
              placeholder="联系人"
              className="block w-full rounded-2xl border border-neutral-300 bg-transparent py-4 pl-6 pr-20 text-base/6 text-neutral-950 ring-4 ring-transparent transition placeholder:text-neutral-500 focus:border-blue-500  focus:outline-none focus:ring-neutral-950/5"
            />
            <div className="absolute inset-y-1 right-1 flex justify-end">

            </div>
          </div>
        </div>
        <div className="flex">
          <div className="relative ">
            <input
              type="text"
              value={phone}
              onChange={textChangeHandler1}
              placeholder="联系方式"
              className="block w-full rounded-2xl border border-neutral-300 bg-transparent py-4 pl-6 pr-20 text-base/6 text-neutral-950 ring-4 ring-transparent transition placeholder:text-neutral-500 focus:border-blue-500 focus:outline-none focus:ring-neutral-950/5"
            />
            <div className="absolute inset-y-1 right-1 flex justify-end">

            </div>
          </div>
        </div>
        {/* <button onClick={saveHandle} className={styles['animated-button']}>
          <span>提交</span>
          <span></span>
        </button> */}
        <button className={styles['menu-btn']} onClick={saveHandle}>
          <span>提 交</span>
          <svg width="34" height="34" viewBox="0 0 74 74" fill="#fff" xmlns="http://www.w3.org/2000/svg">
            <circle cx="37" cy="37" r="35.5" stroke="black" stroke-width="0" ></circle>
            <path d="M25 35.5C24.1716 35.5 23.5 36.1716 23.5 37C23.5 37.8284 24.1716 38.5 25 38.5V35.5ZM49.0607 38.0607C49.6464 37.4749 49.6464 36.5251 49.0607 35.9393L39.5147 26.3934C38.9289 25.8076 37.9792 25.8076 37.3934 26.3934C36.8076 26.9792 36.8076 27.9289 37.3934 28.5147L45.8787 37L37.3934 45.4853C36.8076 46.0711 36.8076 47.0208 37.3934 47.6066C37.9792 48.1924 38.9289 48.1924 39.5147 47.6066L49.0607 38.0607ZM25 38.5L48 38.5V35.5L25 35.5V38.5Z" fill="#4096ff"></path>
          </svg>
        </button>
      </div>
    </>

  )
}

export default function Dashboard() {
  useEffect(() => { }, []);
  const value = useContext(AppContext);
  const { banner, goods } = value;
  const list1 = [goods];


  return (
    <>
      {banner?.length > 0 && (
        <>
          <SwiperList list={value}></SwiperList>
          <SlideIn list={list1} type={1}></SlideIn>
          <SlideIn list={list1} type={2}></SlideIn>
          <SlideIn list={list1} type={3}></SlideIn>
          <CustomQy></CustomQy>
          <CustomMenu></CustomMenu>
        </>
      )}

    </>

  );
}
